package com.hmall.order.mq;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hmall.common.client.ClientFeign;
import com.hmall.common.pojo.item.Item;
import com.hmall.order.constans.StatusConstans;
import com.hmall.order.pojo.Order;
import com.hmall.order.pojo.OrderDetail;
import com.hmall.order.service.IOrderDetailService;
import com.hmall.order.service.IOrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.Objects;
@Slf4j
@Component
public class OrderMQ {
    @Autowired
    private IOrderService orderService;
    @Resource
    private IOrderDetailService orderDetailService;
    @Autowired
    private ClientFeign clientFeign;


    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(name = "order.queue", durable = "true"),
            exchange = @Exchange(name = "order.direct",delayed = "true"),
            key = "order"
    ))
    public void listenXfQueue(String orderId){
        log.info("接收到延迟消息：" + orderId + ",Time:" + LocalDateTime.now());
        // 1-根据订单ID查询订单
        Order order = orderService.getById(orderId);
        if (Objects.isNull(order)) {
            log.error("订单不存在：" + orderId);
        }
        // 判断订单状态是否为1
        if (order.getStatus() != StatusConstans.UNPAID) {
            return;
        }
        if (Objects.nonNull(order.getCloseTime())){
            return;
        }
        // 修改订单状态
        order.setCloseTime(LocalDateTime.now());
        order.setStatus(StatusConstans.TRANSACTION_CANCELLATION_ORDER_CLOSURE);
        orderService.updateById(order);
        // 还原商品库存
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("order_id", orderId);
        OrderDetail orderDetail = orderDetailService.getOne(queryWrapper);
        Integer orderNum = orderDetail.getNum();
        Long itemId = orderDetail.getItemId();
        Item item = clientFeign.seleceById(itemId);
        clientFeign.updateInventory(itemId, item.getStock() + orderNum);
    }
}
